﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using MiniErp.Entity.DataStreams.BOs;
using MiniErp.Entity.DataStreams.DOs;
using MiniErp.Entity.DataStreams.DTOs;
using MiniErp.Mysql.Data;
using MiniErp.Repository.BaseRepository;
using MiniErp.Repository.MysqlRepository.IRepository;
using MiniErp.Repository.UnitOfWorkCore;
using MiniErp.Service.MysqlService.IService;
using System;
using System.Threading.Tasks;

namespace MiniErp.Service.MysqlService.Service
{
    public class LoginService : ILoginService
    {
        private readonly IMysqlUnitOfWork _mysqlUnitOfWork;
        private readonly BaseRepository<MysqlContext, UserInfo> _uir;
        private readonly IMapper _mapper;
        public LoginService(IMapper mapper, IMysqlUnitOfWork mysqlUnitOfWork)
        {
            _mysqlUnitOfWork = mysqlUnitOfWork;
            _uir = mysqlUnitOfWork.Repository<MysqlContext, UserInfo>();
            _mapper = mapper;
        }


        public async Task<UserDTO> Login(LoginDTO logins)
        {
            if (logins.UId == 0 || string.IsNullOrWhiteSpace(logins.PassWord))
            {
                throw new ExceptionBO("用户名或者密码不能为空");
            }
            var num = await _uir.GetInfoNumsAsync(item => item.UId == logins.UId);
            if (num == 0)
            {
                throw new ExceptionBO($"不存在工号为{logins.UId}的用户");
            }
            else if (num == 1)
            {
                var userInfo = await _uir.GetInfoAsync(item => item.UId == logins.UId && item.PassWord == logins.PassWord);
                return userInfo == null
                    ? throw new ExceptionBO("用户名或者密码错误")
                    : _mapper.Map<UserDTO>(userInfo);
            }
            throw new ExceptionBO("该用户账号信息异常");
        }



        public async Task<bool> Register(RegisterDTO registers)
        {
            //生成新用户
            var users = _mapper.Map<UserInfo>(registers);
            users.RightsId = 4;
            users.State = true;
            _uir.AddInfoAsync(users);
            return await _mysqlUnitOfWork.SaveAsync() == 0
                ? throw new ExceptionBO("注册失败")
                : true;
        }


    }
}
